package com.gl.goods.net;

import android.content.Intent;
import android.util.Log;

import com.gl.goods.base.ErrorMessageBean;
import com.gl.goods.base.MyApplication;
import com.gl.goods.ui.login.activity.LoginActivity;
import com.gl.library.tool.RxSPTool;
import com.gl.library.tool.RxTool;
import com.gl.library.utils.StringUtils;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.HttpException;

/**
 * Time; 2020/3/13
 * Author: hmc
 * Description:获取异常信息
 */
public class GetResultErrorMessage {
    private String error_message;
    private static volatile GetResultErrorMessage instance;

    public static GetResultErrorMessage getInstance() {
        if (instance == null) {
            synchronized (RetrofitClient.class) {
                if (instance == null) {
                    instance = new GetResultErrorMessage();
                }
            }
        }
        return instance;
    }

    public String GetResultErrorMessage(Throwable throwable) {
        //当服务器 返回 非200的时候  body 里有返回信息 信息展示
        ResponseBody body = ((HttpException) throwable).response().errorBody();
        try {
            Gson gson = new Gson();
            ErrorMessageBean bean = gson.fromJson(body.string(), ErrorMessageBean.class);
            if (StringUtils.isNotNull(bean)){
                if (bean.getCode() == -1){
                    MyApplication.getInstance().logout();
                    RxSPTool.putInt(RxTool.getContext(), "uid", 0);
                    RxSPTool.putString(RxTool.getContext(), "token", "");
                    Intent i = new Intent(RxTool.getContext(), LoginActivity.class);
                    i.putExtra("type","403");
                    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    RxTool.getContext().startActivity(i);
                }
                error_message = bean.getMessage();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return error_message;
    }
}
